package com.firefly.admin.common.utils;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.util.Objects;

public class ExcelImportUtil {

    private static final String EXCEL_FILE_SUFFIX_1 = "xls";
    private static final String EXCEL_FILE_SUFFIX_2 = "xlsx";

    /**
     * 校验是否为Excel文件
     *
     * @param file 文件
     * @return 校验结果
     */
    public static boolean isExcelFile(MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            if (StringUtils.isBlank(fileName)) {
                return false;
            }
            String fileSuffix = fileName.substring(file.getOriginalFilename().lastIndexOf(StringPool.DOT));
            if (!EXCEL_FILE_SUFFIX_1.equals(fileSuffix) && !EXCEL_FILE_SUFFIX_2.equals(fileSuffix)) {
                return false;
            }
            FileMagic fileMagic = FileMagic.valueOf(new BufferedInputStream(file.getInputStream()));
            return Objects.equals(fileMagic, FileMagic.OLE2) || Objects.equals(fileMagic, FileMagic.OOXML);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
